import { fileURLToPath } from "url"; // 从 url 模块导入 fileURLToPath
import { dirname, join, resolve } from "path"; // 从 path 模块导入 dirname 和 join
import {
  createWriteStream,
  existsSync,
  mkdirSync,
  readFileSync,
  writeFileSync,
} from "fs";

// 获取当前模块的路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const __rootname = resolve(__dirname, "../..");
// ip.txt路径
const ipFilePath = join(__rootname, "ip.txt");

// 创建 ip.txt
// 判断时候存在文件 ip.txt

if (!existsSync(ipFilePath)) {
  console.log("没有 ip.txt 文件，创建一个");
  writeFileSync(ipFilePath, "");
}

// 从头追加写入ip
function writeIp(ip) {
  const content = readFileSync(ipFilePath, "utf-8");
  console.log("🚀 ~ content:", content);
  const updatedContent = ip + "\n" + content;
  console.log("🚀 ~ writeIp ~ updatedContent:", updatedContent);

  writeFileSync(ipFilePath, updatedContent, (error) => {
    if (error) {
      console.error("写入ip.txt时发生错误", error);
      throw new Error(error);
    } else {
      console.log("保存ip成功");
    }
  });
}

export function useIp() {
  let ipChangeCallback = () => {};

  const onChange = (callback) => {
    ipChangeCallback = callback;
  };

  const setIp = (ip) => {
    // 读取 ip.txt
    const fileContent = readFileSync(ipFilePath, "utf8");
    console.log("🚀 ~ setIp--ip.txt文件内容：\n", fileContent);
    // 提取第一行
    const oldIp = fileContent.split("\n")[0].trim();
    console.log("🚀 ~ setIp ~ ip.txt中保存的ip:", oldIp);
    // 比较ip
    if (oldIp === ip) return;
    console.log("ip有变化，写入新的ip到ip.txt文件");
    // ip变化
    writeIp(ip);
    // 触发回调
    ipChangeCallback(ip);
  };
  return {
    onChange,
    setIp,
  };
}
